const jsonServer = require("json-server");
const { initialize } = require("express-openapi");
const swaggerUi = require("swagger-ui-express");

const app = jsonServer.create();
const router = jsonServer.router("./db.json");
require("dotenv").config({ path: "./.env" });

initialize({
  app,
  docsPath: "/api-docs",
  validateApiDoc: true,
  apiDoc: require("./api-v1/api-doc"),
  dependencies: {
    dbService: router.db,
    // worldsService: require("./api-v1/services/worldsService"),
  },
  paths: "./api-v1/paths",
}).then(({ args }) => {
  const { apiDoc, app, docsPath } = args;
  const basePath = apiDoc.basePath;
  
  // 业务路由
  app.use(basePath, router);

  // swagger-ui
  app.use(
    "/api-documentation",
    swaggerUi.serve,
    swaggerUi.setup(null, {
      swaggerOptions: {
        url: `http://${process.env.HOST}:${process.env.PORT}${basePath}${docsPath}`,
      },
    })
  );

  // 默认配置
  app.use(jsonServer.defaults({ bodyParser: true }));

  // 1. 拦截所有请求 authorization Bearer or token
  app.use(require("./middlewares/verifyJWT.js")());

  // 2. ACL权限控制
  app.use(require("./middlewares/acl.js")(router.db));

  // 初始化用户管理（无需登录和权限）
  app.get("/init", require("./middlewares/init.js")(router.db));

  // 登录（无需登录和权限）
  // app.use(require("./router/login.js")());

  // 导入路由
  // app.use(require("./router/users.js")());

  // db.json 业务路由
  app.use(basePath, router);

  // 启动服务器
  app.listen(process.env.PORT, process.env.HOST, () => {
    console.log("Server http://%s:%s", process.env.HOST, process.env.PORT);
    console.log(
      "Docs http://%s:%s/api-documentation",
      process.env.HOST,
      process.env.PORT
    );
  });
});
